﻿var environment = environment ||
{
    getGroupes: window.prefixURL + "Group/GetGroupes",
    getGroup: window.prefixURL + "Group/GetGroup",
    delGroup: window.prefixURL + "Group/DeleteGroup",
    addOrUpdateGroup: window.prefixURL + "Group/AddOrUpdateGroupX",

    getEnvironmentInfoes: window.prefixURL + "Environment/GetEnvironmentInfoes",
    getBusinessInfoes: window.prefixURL + "Business/GetBusinessInfoesByEnvId",
    getApplicationInfoes: window.prefixURL + "Application/GetApplicationInfoesByBusinessId",

    bodyTpl: _.template($("#listTemplate").html()),
    pagerTpl: _.template($("#pagingTablePager").html()),

    pageIndex: function () {
        return $('#nav').find('li[flag]').find('a').html();
    },
    pageSize: function () {
        return $('#nav').find('.pagingTablePageCountSelect').val();
    },

    getList: function (pageIndex) {
        var t = this;
        var url = t.getGroupes + "?pageIndex=" + pageIndex + "&pageSize=10";
        $.ajax({
            url: url,
            type: "GET",
            dataType: "Json",
            success: function (data) {
                if (data != null) {
                    $("#tbody").html(t.bodyTpl(data.returnObj));
                    $("#nav").html(t.pagerTpl(data.pager));
                    $(".pagingTablePageCountSelect").val(data.pager.PageSize);
                }
            },
            error: function (data) {

            }
        });
    },

    del: function (sender, id) {
        var returnVal = confirm("Are you sure？");
        if (returnVal === false) {
            return;
        } else {
            $.ajax({
                url: sender.delGroup + "?id=" + id,
                type: "GET",
                dataType: "Json",
                success: function (data) {
                    if (data.returnObj === true) {
                        alert("Success！");
                        sender.getList(1);
                    } else {
                        alert("Error:" + data.businessMessage);
                    }
                }
            });
        }
    },

    edit: function (sender, id) {
        $.ajax({
            url: sender.getGroup + "?id=" + id,
            type: "GET",
            dataType: "Json",
            success: function (data) {
                if (data.businessMessage !== -1) {
                    $("#txtGroupId").val(data.returnObj.id);
                    $("#txtName").val(data.returnObj.name);
                    $("#txtDecription").val(data.returnObj.description);
                    $("#createModel").modal();
                } else {
                    alert(data.businessMessage);
                }
            },
            error: function (data) {
                alert("Error:" + data);
            }
        });
    },

    getEnvList: function() {
        var t = this;
        var url = t.getEnvironmentInfoes + "?pageIndex=1&pageSize=999999";
        $.ajax({
            url: url,
            type: "GET",
            dataType: "Json",
            success: function (data) {
                if (data != null) {
                    $("#select_EnvironmentInfo").empty();
                    $("#select_EnvironmentInfo").append("<option value=''>&#x2014;&#x2014;选择环境&#x2014;&#x2014;</option>");
                    $.each(data.returnObj, function (key, val) {
                        $("#select_EnvironmentInfo").append("<option value='"+val.id+"'>"+val.name+"</option>");
                    });
                }
            },
            error: function (data) {

            }
        });
    },

    getBusinessList: function (environmentInfoId) {
        var t = this;
        var url = t.getBusinessInfoes + "?environmentInfoId=" + environmentInfoId;
        $.ajax({
            url: url,
            type: "GET",
            dataType: "Json",
            success: function (data) {
                if (data != null) {
                    $("#select_Business").empty();
                    $("#select_Business").append("<option value=''>&#x2014;&#x2014;选择业务&#x2014;&#x2014;</option>");
                    $.each(data.returnObj, function (key, val) {
                        $("#select_Business").append("<option value='" + val.id + "'>" + val.name + "</option>");
                    });
                }
            },
            error: function (data) {

            }
        });
    },

    getApplicationList: function (businessId) {
        var t = this;
        var url = t.getApplicationInfoes + "?businessId=" + businessId;
        $.ajax({
            url: url,
            type: "GET",
            dataType: "Json",
            success: function (data) {
                if (data != null) {
                    $("#select_Application").empty();
                    $("#select_Application").append("<option value=''>&#x2014;&#x2014;选择应用程序&#x2014;&#x2014;</option>");
                    $.each(data.returnObj, function (key, val) {
                        $("#select_Application").append("<option value='" + val.id + "'>" + val.name + "</option>");
                    });
                }
            },
            error: function (data) {

            }
        });
    },

    initPage: function () {
        var t = this;
        t.getList(1);
        t.getEnvList();
    },

    bindEvents: function () {
        var t = this;

        $("span[name='opt-create']").bind("click", function () {
            $("#txtGroupId").val("");
            $("#txtName").val("");
            $("#txtDecription").val("");
            $("#createModel").modal();
        });

        $("#tbody").delegate("tr td span", "click", function () {
            var type = $(this).data("type");
            var id = $(this).data("id");
            if (type === "edit") {
                t.edit(t, id);
            } else {
                t.del(t, id);
            }
        });

        $("#btnSubmit").bind("click", function () {

            var $btn = $(this).button("loading...");
            var name = $("#txtName").val();
            var businessInfo = {};
            var applicationInfo = {};
            var hostInfo = {};
            if ($("#select_Business").val() != "")
                businessInfo = { "BusinessId": $("#select_Business").val() };
            if ($("#select_Application").val() != "")
                applicationInfo = { "ApplicationId": $("#select_Application").val() };

            var i = 0;
            $("select[name='select_host_key']").each(function () {
                var key = $(this).val();
                var value = $("input[name='select_host_value']")[i].value;

                if (key != "" && value != "")
                    hostInfo[key] = value;
                i++;
            });

            $.ajax({
                url: t.addOrUpdateGroup,
                type: "POST",
                dataType: "Json",
                data: {
                    Name: name,
                    BusinessInfo: businessInfo,
                    ApplicationInfo: applicationInfo,
                    HostInfo: hostInfo
                },
                success: function (data) {
                    if (data.returnObj === true) {
                        $("#createModel").modal('hide');
                        $btn.button('reset');
                        t.getList(1);
                    } else {
                        $("#createErrorMsg").show().children("div").find("span").html(data.businessMessage);
                        $btn.button('reset');
                    }
                },
                error: function (event) {
                    alert("Error:" + event);
                }
            });
        });

        $("#select_EnvironmentInfo").bind("change", function () {
            if ($(this).val() != "") {
                t.getBusinessList($(this).val());
            }
        });

        $("#select_Business").bind("change", function () {
            if ($(this).val() != "") {
                t.getApplicationList($(this).val());
            }
        });

        $("#nav").delegate("ul li:not('.disabled')", 'click', function () {
            var arialabel = $(this).children('a').attr('aria-label');
            var pageIndex = $(this).children('a').attr('data-page');
            var activePageIndex = t.pageIndex();
            if (arialabel != undefined) {
                if (arialabel === 'Previous') {
                    t.getList(parseInt(activePageIndex) - 1);
                } else if (arialabel === 'Next') {
                    t.getList(parseInt(activePageIndex) + 1);
                }
            } else {
                t.getList(pageIndex);
            }
        });
    },

    reBindEvents: function() {
        var t = this;
        $(":button[name='button_remove']").unbind();
        $(":button[name='button_add']").unbind();

        $(":button[name='button_remove']").bind("click", function () {
            if($("#host_group").children().length > 1)
                $(this).parent().parent().parent().remove();
        });

        $(":button[name='button_add']").bind("click", function () {
            var ss = "<div class='form-group'><div class='col-sm-3'><select class='form-control' name='select_host_key'><option value=''>—主机属性</option><option value='OS'>操作系统</option><option value='InnerIP'>内网IP</option><option value='OuterIP'>外网IP</option><option value='CPU'>CPU</option><option value='HardDiskSize'>硬盘容量(GB)</option><option value='RAM'>内存容量(GB)</option><option value='Status'>运行状态</option><option value='CreateTime'>创建时间</option><option value='ExpireTime'>到期时间</option></select></div><div class='col-sm-5'><input type='text' class='form-control' aria-describedby='basic-addon1' name='select_host_value'></div><div class='col-sm-4'><div class='btn-group' role='group' aria-label='...'><button type='button' class='btn btn-default' name='button_add'>+</button><button type='button' class='btn btn-default' name='button_remove'>X</button></div></div></div>";
            $("#host_group").append(ss);
            t.reBindEvents();
        });
    },

    //@入口方法
    init: function () {
        var t = this;
        t.bindEvents();
        t.initPage();
        t.reBindEvents();
    }
}.init();